package com.zhulanhua.blogs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhulanhua.blogs.Utils.MailUtils;
import com.zhulanhua.blogs.dao.FriendLinkDao;
import com.zhulanhua.blogs.dao.UserDao;
import com.zhulanhua.blogs.domain.FriendLink;
import com.zhulanhua.blogs.exception.BusinessException;
import com.zhulanhua.blogs.service.FriendLinkSerice;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Log4j2
public class FriendLinkServiceImpl implements FriendLinkSerice {

    @Autowired
    FriendLinkDao friendLinkDao;

    @Autowired
    UserDao userDao;

    @Autowired
    MailUtils mailUtils;

    @Override
    public List<FriendLink> getNO(int examine) {
        QueryWrapper<FriendLink> qw = new QueryWrapper<>();
        qw.lambda().eq(FriendLink::getFriendStatus, examine);
        return friendLinkDao.selectList(qw);
    }

    @Override
    public boolean save(FriendLink friendLink) {
        friendLink.setCreateTime(System.currentTimeMillis() + "");
        return friendLinkDao.insert(friendLink) == 1;
    }

    @Override
    public boolean delete(int id) {
        return friendLinkDao.deleteById(id) == 1;
    }

    @Override
    public boolean update(int id, int examine) {
        FriendLink friendLink = friendLinkDao.selectById(id);
        FriendLink f = new FriendLink();
        f.setFriendStatus(examine);
        f.setFriendId(id);
        String cent = null;
        if (examine == 1){
            //审核通过
            cent = "<h1>个人博客</h1>" +
                    "<h3>恭喜您！你发布的友链审核通过了</h3>";
        }else if (examine == 2){
            //审核不通过
            cent = "<h1>个人博客</h1>" +
                    "<h3>很遗憾！你发布的友链审核未通过</h3>";
        }

        if (cent != null){
            //发邮件
            try {
                mailUtils.sendHtmlMailMessage(friendLink.getFriendMail(), "个人博客", cent);
            }catch (BusinessException e){
                log.error(e.getMessage() + "，友链邮箱有误" + friendLink.getFriendMail());
            }
        }
        return friendLinkDao.updateById(f) == 1;
    }
}
